package com.mer.handler;

import com.alibaba.fastjson.JSON;
import com.mer.utils.MapperUtils;
import com.mer.utils.OkHttpClientUtil;
import com.mer.utils.Result;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Component
public class MySuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    @Value("${oauth.token.url}")
    private String url;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        /*//获取输入的密码123
        String password = httpServletRequest.getParameter("password");
        //获取认证成功后用户的信息
        User principal = (User) authentication.getPrincipal();// User
        Map<String, String> params = new HashMap();
        params.put("username", principal.getUsername());
        params.put("password",password);
        params.put("grant_type", "password");
        params.put("client_id", "myapp");
        params.put("client_secret", "lxapp");
        Map<String,Object> result=new HashMap<>();
        try {
            // 解析响应结果封装并返回  java端 发生请求地址.httpclient
            Response response1 = OkHttpClientUtil.getInstance().postData(url, params);
            //接受请求响应的结果
            String jsonString = Objects.requireNonNull(response1.body()).string();
            Map<String, Object> jsonMap = MapperUtils.json2map(jsonString);
            System.out.println("============="+jsonMap);
            String token = String.valueOf(jsonMap.get("access_token"));
            System.out.println("token====="+token);
            result.put("token", token);
            result.put("authorities",principal.getAuthorities());

        } catch (Exception e) {
            e.printStackTrace();
        }
        Result r=new Result(200,"登录成功",result);
        String jsonmessage= JSON.toJSONString(r);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(jsonmessage);
        out.flush();
        out.close();*/
    }
}
